package com.bdqn.controller;

import com.bdqn.pojo.SysUser;

import com.bdqn.service.SysUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class IndexController {

    @Resource
    private SysUserService sysUserService;
    @GetMapping("/login")
    public String login(){
        return "login";
    }
    @GetMapping("/main")
    public String main(){
        return "main";
    }
    @RequestMapping("/login")
    public String doLogin(Model model, HttpServletRequest request, HttpSession session, String usrName, String usrPassword){
//        SysUser user = sysUserService.login(usrName, usrPassword);
//        if (user != null ){
//            request.getSession().setAttribute("loginUser",user);
//            return "main";
//        }else {
//            return "login";
//        }
        try{
            UsernamePasswordToken token = new UsernamePasswordToken(usrName,usrPassword);
            Subject subject = SecurityUtils.getSubject();
            SysUser user = (SysUser) subject.getPrincipal();
            session.setAttribute("loginUser",user);
            return "redirect:/main";
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            model.addAttribute("msg","用户名或密码错误，登录失败");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("msg","用户被禁用，登录失败");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("msg","认证异常，登录失败");
            return "login";
        }
    }

   @GetMapping("/logout")
   public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        session.invalidate();
        SecurityUtils.getSubject().logout();
       return "redirect:/login";
   }
}